<template>
  <div id="purposeDetailDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="isEmpty(purposeId)" @click="findPurposeDetailList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="isEmpty(purposeId)" @click="addPurposeDetail"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="isEmpty(purposeId)" @click="saveBathPurposeDetail"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="isEmpty(purposeId)" @click="deletePurposeDetail"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="purposeDetailTableRef" class="mytable-scrollbar" border="inner" align="left" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="detailList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="seq" title="序号" width="50" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.seq" type="number"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="sampleTypeId" title="标本类型" width="100" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.sampleTypeName }}</span>
          </template>
          <template #edit="{ row, rowIndex, column }">
            <SelectDataGrid :url="'/api/lab/labSampleType/findSampleTypeList'" :column="[
                          { field: 'sampleTypeCode', title: '编码' },
                          { field: 'sampleTypeName', title: '名称' }
                        ]" :searchParam="{ isStop: 'false' }" :isPage="false" @SelectCellClick="
                          (e) => {
                            selectSampleTypeRow(e, rowIndex);
                          }
                        " :showField="'sampleTypeName'">
            </SelectDataGrid>
          </template>
        </vxe-column>
        <vxe-column field="sxWorkFlowId" title="方案流程" width="200" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ row.sxWorkFlowName }}</span>
          </template>
          <template #edit="{ row, rowIndex, column }">
            <SelectDataGrid :url="'/api/bac/bac-work-flow/findBacWorkFlowList'" :column="[
                          { field: 'workFlowCode', title: '编码' },
                          { field: 'workFlowName', title: '名称' }
                        ]" :searchParam="{ isStop: 'false' }" :isPage="false" @SelectCellClick="
                          (e) => {
                            selectSxWorkFlowRow(e, rowIndex);
                          }
                        " :showField="'workFlowName'">
            </SelectDataGrid>
          </template>
        </vxe-column>
        <vxe-column field="sxCulCombinaNos" title="培养基组合" width="300" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ formatCultureCombinationNameByIds(row) }}</span>
          </template>

          <template #edit="{ row,rowIndex }">
            <SelectDataCheckedList :url="'/api/bac/bac-cultrue-combination/findBacCultureCombinationList'" ref="ruleSelectListRef" :column="[
                      { field: 'code', title: '编号' }, //列标题
                      { field: 'name', title: '名称' }
                    ]" :searchParam="{}" :isPage="false" @SelectCellClick="
                      (e) => {
                        selectSxCultureCombinationRow(e, rowIndex);
                      }
                    " :clickRowId="row.culComninaNo">
            </SelectDataCheckedList>
          </template>

        </vxe-column>
        <vxe-column field="sampleRemark" title="标本备注" width="200" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.sampleRemark" placeholder="" type="text"></vxe-input>
          </template>
        </vxe-column>

      </vxe-table>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';

let store = AppStore();
defineExpose({ initPage });
let purposeId = null;
let purposeNo = null;
let cultureCombinationList: any = reactive([]);
let detailList: any = reactive([]);
let rloading = ref(false);

function initPage(row: any) {
  purposeId = row.id;
  purposeNo = row.purposeNo;
  findPurposeDetailList();
  getCultureCombinationList();
}
async function getCultureCombinationList() {
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationList';
  const data = await proxy.$http.get(url);
  cultureCombinationList.push(...data.data);
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findPurposeDetailList() {
  rloading.value = true;
  detailList.length = 0; //放入数据前清空数据
  if (isEmpty(purposeId)) {
    rloading.value = false;
    return;
  }
  const url = '/api/bac/bacReqPurposeDetail/findPurposeDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { purposeNo: purposeNo }
    })
    .then((res: any) => {
      detailList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

function addPurposeDetail() {
  if (isEmpty(purposeId)) {
    VxeMessage('请选择目的', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      purposeId: purposeId,
      purposeNo: purposeNo,
      sampleTypeId: '',
      sampleTypeCode: '',
      sampleTypeName: '',
      sampleRemark: '',
      sxWorkFlowId: '',
      sxWorkFlowNo: '',
      flowNo: '',
      bxFlowNo: '',
      sxWorkFlowName: '',
      sxCulCombinaNos: '',
      culComninaNo: '',
      bxWorkFlowId: '',
      bxWorkFlowNo: '',
      bxCulCombinaNos: '',
      bxWorkFlowName: '',
      bxCultureCombinationIds: '',
      seq: detailList.length + 1,
      orgId: store.userInfo.orgId
    };
    detailList.push(record);
  }
}

// 左侧保存
async function saveBathPurposeDetail() {
  if (isEmpty(purposeId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.purposeDetailTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = detailList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateDetail = [] as any[];
      updateRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          purposeId: e.purposeId,
          purposeNo: e.purposeNo,
          sampleTypeId: e.sampleTypeId,
          sampleTypeCode: e.sampleTypeCode,
          sampleRemark: e.sampleRemark,
          sxWorkFlowId: e.sxWorkFlowId,
          sxWorkFlowNo: e.sxWorkFlowNo,
          sxCulCombinaNos: e.sxCulCombinaNos,
          bxWorkFlowId: e.bxWorkFlowId,
          bxWorkFlowNo: e.bxWorkFlowNo,
          bxCultureCombinationIds: e.bxCultureCombinationIds,
          seq: e.seq,
          orgId: e.orgId
        };

        sveOrupdateDetail.push(iDetail);
      });
      InsertRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          purposeId: e.purposeId,
          purposeNo: e.purposeNo,
          sampleTypeId: e.sampleTypeId,
          sampleTypeCode: e.sampleTypeCode,
          sampleRemark: e.sampleRemark,
          sxWorkFlowId: e.sxWorkFlowId,
          sxWorkFlowNo: e.sxWorkFlowNo,
          sxCulCombinaNos: e.sxCulCombinaNos,
          bxWorkFlowId: e.bxWorkFlowId,
          bxWorkFlowNo: e.bxWorkFlowNo,
          bxCultureCombinationIds: e.bxCultureCombinationIds,
          seq: e.seq,
          orgId: e.orgId
        };
        sveOrupdateDetail.push(iDetail);
      });

      if (sveOrupdateDetail.length > 0) {
        const url = '/api/bac/bacReqPurposeDetail/saveOrUpdatePurposeDetail';
        const obj: any = {};
        obj.detailList = sveOrupdateDetail;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            findPurposeDetailList();
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deletePurposeDetail() {
  const sltDetails = (proxy.$refs.purposeDetailTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDetailList = sltDetails.filter((p: any) => !isEmpty(p.id));
        if (delDetailList.length > 0) {
          const data = { detailList: delDetailList };
          const url = '/api/bac/bacReqPurposeDetail/deleteBatchPurposeDetail';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findPurposeDetailList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeDetailList = sltDetails.filter((p: any) => isEmpty(p.id));
        if (removeDetailList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.purposeDetailTableRef;
          if ($Xtable) {
            for (const removeRow of removeDetailList) {
              detailList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 获取组件当前行数据
function selectSampleTypeRow(row, index) {
  detailList[index].sampleTypeName = row.sampleTypeName;
  detailList[index].sampleTypeId = row.id;
  detailList[index].sampleTypeCode = row.sampleTypeCode;
}
function selectSxWorkFlowRow(row, index) {
  detailList[index].sxWorkFlowName = row.workFlowName;
  detailList[index].sxWorkFlowId = row.id;
  detailList[index].sxWorkFlowNo = row.workFlowCode;
  detailList[index].flowNo = row.workFlowCode;
}
function selectSxCultureCombinationRow(row, index) {
  const nameArr = [];
  const idArr = [];
  let nos = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    idArr.push(item.id);
    nos.push(item.code);
  });
  const noString = nos.join(',');
  detailList[index].sxCulCombinaNos = noString;
  detailList[index].culComninaNo = nos;
}

function formatCultureCombinationNameByIds(row) {
  if (!isEmpty(row.sxCulCombinaNos)) {
    const ruleNames: any = [];
    const ruelIdList = row.sxCulCombinaNos.split(',');
    for (const ruelId of ruelIdList) {
      const item = cultureCombinationList.find((item) => item.code === ruelId);
      if (!isEmpty(item)) {
        ruleNames.push(item.name);
      }
    }
    return ruleNames.join(',');
  } else {
    return '';
  }

  // qcRuleList.filter(p=>p.isVisiable)

  // const obj = materialItemList.filter((p: any) => {
  //   defaultSelecteRowKeys.push(p.qcItemId);
  //   return p.qcItemId == row.id;
  // });
}
</script>

<style lang="scss" scoped>
#purposeDetailDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
